package util;

import com.example.bean.UidInfo;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import util.utilmysql.UtilDruid;

import java.text.ParseException;
import java.util.List;

public class UidCtrl {
    private static final JdbcTemplate jdbcTemplate;
    private static final int limitTime = 3600000;// 超时时间:一小时

    static {
        jdbcTemplate = new JdbcTemplate(UtilDruid.getDateSource());
    }

    public static String checkUid(String uid) {
        List<UidInfo> query = jdbcTemplate.query("select * from second_hand.uid where uid = ?", new BeanPropertyRowMapper<>(UidInfo.class), uid);
        if (query.size() == 0) {
            return "0";// 系统中无匹配的 Uid
        } else {
            try {
                if (UtilTime.getUnixTime(query.get(0).getTime()) - UtilTime.getUnixTimeLNow() > -limitTime) {
                    updateUid(uid);
                    return String.valueOf(query.get(0).getAccount());
                } else {
                    deleteUid(uid);
                    return "-1";// Uid 登录超时
                }
            } catch (ParseException e) {
                e.printStackTrace();
                return "-2";// 返回时间格式错误
            }
        }
    }

    public static String getUid(int account) {
        return createUid(account);
    }

    private static String createUid(int account) {
        int count;
        String uid;
        do {
            long rand = (long) (Math.random() * 10000000000L);
            uid = String.format("%5d", rand).replace(" ", "0");
            count = jdbcTemplate.queryForObject("select count(uid) from second_hand.uid where uid=?", Integer.class, uid);
        } while (count != 0);
        jdbcTemplate.update("delete from second_hand.uid where account=?", account);
        jdbcTemplate.update("insert into second_hand.uid(uid,time,account) values (?,?,?)", uid, UtilTime.getStringTimeNow(), account);
        return uid;
    }

    private static void updateUid(String uid) {
        jdbcTemplate.update("update second_hand.uid set time =? where uid=?", UtilTime.getStringTimeNow(), uid);
    }

    private static void deleteUid(String uid) {
        jdbcTemplate.update("delete from second_hand.uid where uid=?", UtilTime.getStringTimeNow(), uid);
    }
}
